<template>
	<div>
		<div class="audio-bar"
		ref="audiobar"
		:class="{isPlay: isPlay}">
			<span v-if="!isLoaded && isIOS" @click="play">点击加载音频</span>
			<span v-if="!isLoaded && !isIOS">音频加载中…</span>
			<span v-if="isLoaded" @click="play">{{duration}} s</span>
		</div>
		<audio ref="audio" :src="src"></audio>
		<!-- <p id="loadStatus">LOADING...</p> -->
	</div>
</template>
<script>
import {myAlert} from '../assets/js/utils.js'
import {isIOS} from '../assets/js/global.js'
export default{
	name: 'playaudio',
	data(){
		return{
			isPlay: false,
			isLoaded: false,
			duration: 0.00,
			isIOS: isIOS
		}
	},
	mounted(){
		let audio = this.$refs.audio, self = this;
		function audioLoaded() {
		    self.duration = (audio.duration/2).toFixed(2);
		    self.isLoaded = true;
		    self.$refs.audiobar.style.width =  1 + audio.duration/2/10+'rem';
		}
		function audioEnd() {
			myAlert.small('播放完毕');
			self.isPlay = false;
		}
  		audio.addEventListener('canplaythrough', audioLoaded, false);
  		audio.addEventListener('ended', audioEnd, false);
  		audio.load();
	},
	methods:{
		play(){
			let audio = this.$refs.audio;
			if(!this.isPlay) {
				audio.play();
				myAlert.small('开始播放');
			}
			else {
				audio.pause();
				audio.currentTime = 0;
				myAlert.small('停止播放');
			}
			this.isPlay = !this.isPlay;
		}
	},
	props:['src']
}
</script>
<style lang='less' scoped>
.audio-bar{
	min-width: 2rem;
	max-width: 7rem;
	height: 0.64rem;
	border-radius: 0.05rem;
	display: inline-block;
	margin-top: .2rem;
	background: url(.././assets/img/yuyin.png) no-repeat .2rem center;
	background-size: 0.32rem 0.4rem;
	background-color: #6db1ff;
	padding-left: .5rem;
	&.isPlay{
		background-image: url(.././assets/img/yuyin2.gif);
	}
	span{
		color: #fff;
		font-size: .3rem;
		line-height: .64rem;
		padding: 0 .2rem;
	}
}
</style>